/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lu.med.praxiswahl.wahlumed.dao.beans;

import java.util.Collection;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import lu.med.praxiswahl.wahlumed.dao.beans.daointerface.BillContentsDAOInt;
import lu.med.praxiswahl.wahlumed.model.beans.BillsContentsTBL;

/**
 * 
 * @author Patrick kendzo Email: pkendzo@msn.com
 */

@Stateless
public class BillContentsDAO implements BillContentsDAOInt
{

    @PersistenceContext(unitName = "gynaekomedic-ejbPU")
    private EntityManager em = null;

    public BillContentsDAO()
    {

    }

    @Override
    public void delete(Long todo)
    {

	BillsContentsTBL bill = em.find(BillsContentsTBL.class, todo);
	if (bill != null)
	{
	    em.remove(bill);
	    em.flush();
	}

    }

    @Override
    public Collection<BillsContentsTBL> findAvailableBillContentsByBillNumber(
	    Long billNumber)
    {
	// TODO Auto-generated method stub
	return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<BillsContentsTBL> findBillsContentByBillNumber(Long billNumber)
    {
	/*
	 * try { return (List<BillsContentsTBL>) em.createQuery(
	 * "select bc from BillsContentsTBL bc where rechnungs_nummer = '" +
	 * billNumber + "'").getResultList(); } catch (Exception e) { throw new
	 * RuntimeException("No BillContens for this bill", e); }
	 */

	try
	{
	    /*
	     * return (List<BillsContentsTBL>) em.createQuery(
	     * "select * from BillsContentsTBL bc join fetch CodeRatesTBL c on (bc.code_tarif = c.label "
	     * + "and bc.rechnungs_nummer = '"+
	     * billNumber+"') order by c.prioritaet desc").getResultList();
	     */

	    return (List<BillsContentsTBL>) em
		    .createNativeQuery(
			    "SELECT d.RECHNUNGS_DETAILS_ID, d.date_dent_heure,"
				    + "d.h, d.med, d.code_tarif, d.nbr, d.montant, d.med_pres, d.RECHNUNGS_ID FROM praxis.praxis_rechnungs_details d  join praxis.praxis_cotarife c "
				    + "on (d.code_tarif = c.label and d.RECHNUNGS_ID='"
				    + billNumber
				    + "') order by STR_TO_DATE(d.date_dent_heure,'%d.%m.%Y') asc, c.PRIORITAET desc",
			    BillsContentsTBL.class).getResultList();
	}
	catch (Exception e)
	{
	    throw new RuntimeException("No BillContens for this bill", e);
	}
    }

    @Override
    public BillsContentsTBL findBillsContentByID(Long id)
    {
	return (BillsContentsTBL) em.find(BillsContentsTBL.class, id);
    }

    @Override
    public void persist(BillsContentsTBL todo)
    {
	em.persist(todo);
	em.flush();

    }

    @Override
    public void update(BillsContentsTBL todo)
    {
	em.merge(todo);
	em.flush();

    }

}
